package database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DeptDaolmpl implements DeptDao {
    // 定义变量
    private Connection conn;
    private PreparedStatement pstmt;
    private ResultSet rs;

    // 两个表之间查找信息
    @Override
    public List<Dept> findDepts() {
        List<Dept> depts = new ArrayList<Dept>();
        Dept dept = null;
        Emp emp = null;
        try {
            conn = JDBCDemo.getConnection();
            pstmt = conn.prepareStatement("select e.ename,d.dname,d.loc from emp e,dept d where e.deptno=d.deptno");
            rs = pstmt.executeQuery();
            while(rs.next()){
                dept = new Dept();
                dept.setDname(rs.getString("dname"));
                dept.setLoc(rs.getString("loc"));
                emp = new Emp();
                emp.setEname(rs.getString("ename"));
                dept.setEmpList(emp);
                depts.add(dept);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            JDBCDemo.closeAll(rs, pstmt, conn);
        }
        return depts;
    }
}
